import {
	Message,
	MessageBox,
	Loading
} from 'element-ui';

import axios from 'axios';
import store from '../../store';
import router from '../../router';

export default {
	/**
	 * 接口请求基路径
	 */
	baseUrl: 'https://api.zwmall.chengdongqing.top/admin',
	/**
	 * 数据请求
	 */
	request(url, data = {}, callback = () => {}, isGet = false, baseUrl = '') {
		axios.request({
			url: url,
			baseURL: baseUrl || this.baseUrl,
			headers: {
				token: store.getters.token,
				'content-type': 'application/x-www-form-urlencoded'
			},
			params: data,
			method: isGet ? 'GET' : 'POST',
		}).then(res => {
			callback(res.data);
		}).catch(res => {
			if (res.response) {
				switch (res.response.status) {
					case 401:
						callback({
							state: 'fail',
							msg: '请重新登录'
						});
						store.commit('logout');
						router.replace('/login');
						break;
					case 403:
						callback({
							state: 'fail',
							msg: '权限不足'
						});
						router.replace('/403');
						break;
					default:
						callback({
							state: 'fail',
							msg: '系统繁忙，请稍后再试...'
						});
						break;
				}
			} else {
				callback({
					state: 'fail',
					msg: '系统繁忙，请稍后再试...'
				});
			}
		});
	},
	/**
	 * 用户主动确认后再发起请求
	 */
	requestWithConfirm(question, url, data, title = '', type = '操作') {
		return new Promise(resolve => {
			MessageBox.confirm(question, title).then(_ => {
				const loading = Loading.service({
					text: '处理中...'
				});
				this.request(url, data, (res) => {
					loading.close();

					if (res.state == 'ok') {
						Message.success(type + '成功');
						resolve();
					} else {
						this.msg(res.msg);
					}
				});
			}).catch(_ => {});
		});
	},
	/**
	 * 格式化时间
	 * @param {Object} time
	 */
	formatTime(time) {
		const array = time.split(' ');
		const units = ['年', '月', '日'];
		const dateStr = array[0].split('-').map((e, i) => {
			return e + units[i];
		}).join('');
		const timeStr = array[1].substr(0, 5);
		return dateStr + ' ' + timeStr;
	},
	/**
	 * 弹出错误消息
	 */
	msg(msg) {
		Message({
			type: 'warning',
			message: msg
		});
		return false;
	}
}
